/**
 * 报事待回复列表
 * @author zhangqiang
 * @date   2016/10/09
 */

import NoData from "../components/NoData";
import PullRefresh from "../components/mui/PullRefresh.js";

(function (lf, r) {
    var ajax = lf.utils.ajax,
        RC = r.createClass,
        getUrlParam = lf.utils.getUrlParam,
        doAction = lf.appJs.doAction;

    const TYPE = getUrlParam('type'),
        UNTREATED = 'untreated',//未处理
        COMPLETED = 'completed',//已完成
        ARCHIVED = 'archived',//已归档
        CLOSE = 'close',//已关闭
        QLLIGCP = 'qlligcp',//待审核
        SENTED = 'sented',//已派单
        CHECK = 'check';//全部报事

    const ALL = 'all',
        MONTH = 'month',
        WEEK = 'week',
        MARK = 'mark';

    let Header = r.createClass({
        getInitialState: function () {
            return {
                headers: [
                    {
                        title: '全部',
                        range: ALL,
                    },
                    {
                        title: '今天',
                        range: MONTH
                    },
                    {
                        title: '本周',
                        range: WEEK
                    },
                    {
                        title: '本月',
                        range: MARK
                    }
                ],
                counts: [],
                userId: '',
            }
        },
        componentDidMount: function () {
            let $links = $('.header a'),
                me = this;

            if (!$links.length) return;
            //默认第一个点中
            $links.eq(0).addClass('active');
            //点击
            $links.each(function () {
                $(this).on('tap', function () {
                    //切换样式,
                    $(this).addClass('active').siblings().removeClass('active');
                    var range = $(this).data('range');
                    me.props.getList(1, false, range);
                    if (TYPE == CHECK) {
                        me.props.resetPage();
                        mui('#pullrefresh').pullRefresh().refresh(true);//refresh again
                    }
                }.bind(this));
            });
        },
        render: function () {
            let max = this.props.maxCount,
                addClass = '',
                headers = this.state.headers.map(function (data, i) {
                    return (
                        <a key={'head-'+i} data-range={data.range} className="item" href="javascript:;">
                            <p>{max[i]}</p>
                            <p className="bold">{data.title}</p>
                            <div className="rectangle"></div>
                        </a>
                    );
                });
            return (
                <div className={"header "+ addClass}>
                    <div className="item-row">
                        {headers}
                    </div>
                    <div className="split-line"></div>
                </div>
            )
        },
    });
    var ListGroup = RC({
        getInitialState: function () {
            return ({
                noData: {
                    span_text: '还没有需要您审核的回复',
                    headerCounts: [0, 0, 0],
                }
            });
        },
        render: function () {
            var setList = this.props.data.map(function (data) {
                return (
                    <List data={data}/>
                )
            })
            if (this.props.data.length) {
                return (
                    <div className="list-group" id="listGroup">
                        {setList}
                    </div>
                )
            } else {
                return <NoData data={this.state.noData}/>
            }
        }
    });
    var List = RC({
        render: function () {
            var data = this.props.data,
                fmt = 'yyyy-MM-dd hh:mm',
                reportTime = lf.utils.format(data.createTime, fmt),
                reviewStatus = this.props.data.reviewStatus;
            return (
                <a className="list mui-table-view" href="javascript:;" ref="toDetail">
                    <div className="list-title">
                        <span className="name">{data.num} {data.name}</span>
                        <span className="time">{reportTime}</span>
                    </div>
                    <p className="list-text">{data.content}</p>
                    <span className="list-name">{data.accepterName}</span>
                </a>
            )
        },
        componentDidMount: function () {
            if (TYPE == UNTREATED) {//待处理
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                        this.props.data.orderId = '';
                    }
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn' +
                        '&type=' + 'UNTREATED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == COMPLETED) {//已完成
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&type=' + 'COMPLETED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == ARCHIVED) {//已归档
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn' +
                        '&type=' + 'ARCHIVED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == CLOSE) {//已关闭
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId
                        + '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' +
                        'fn' + '&type=' + 'CLOSE'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == QLLIGCP) {//待审核
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn'
                        + '&type=' + 'QLLIGCP'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == SENTED) {//已派单
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn'
                        + '&type=' + 'SENTED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == CHECK) {//全部报事
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&state=' + this.props.data.status + '&orderId=' + this.props.data.orderId + '&id='
                        + this.props.data.id + '&last=' + 'fn' + '&type=' + 'CHECK'
                        , '报事详情');
                }.bind(this));
            }
        }
    });

    var Root = r.createClass({
        getInitialState: function () {
            return {
                list: [{
                    reporterName: '',
                    reportTime: '',
                    content: '',
                    houseNum: ''
                }],
                user: '',
                maxCount: [],
                currType: '',
            }
        },
        getList: function (page, shouldAppend, Fn) {
            if (!page) {
                page = 1;
            }

            var me = this,
                typeAdd,
                typeFn;

            if (TYPE == UNTREATED) {//未处理
                typeFn = 0;
            } else if (TYPE == SENTED) {//已派单
                typeFn = 1;
            } else if (TYPE == COMPLETED) {//已完成
                typeFn = 2;
            } else if (TYPE == ARCHIVED) {//已归档
                typeFn = 3;
            } else if (TYPE == CLOSE) {//已关闭
                typeFn = 4;
            } else if (TYPE == QLLIGCP) {//待审核
                typeFn = 5;
            } else if (TYPE == CHECK) {//全部报事
                typeFn;
            }

            if (Fn == 'month') {//今天
                typeAdd = 1;
            } else if (Fn == 'week') {//本周
                typeAdd = 2;
            } else if (Fn == 'mark') {//本月
                typeAdd = 3;
            } else if (Fn == 'all') {//全部
                typeAdd = 0;
            }

            ajax({
                type: 'POST',
                data: {
                    staffId: me.props.user.id,
                    eventReportType: typeFn,
                    timeType: typeAdd,
                    page: page,
                },
                success: function (data) {
                    if (data.code == '200') {

                        let resultList = data.dataList,
                            maxCount = data.maxCount,
                            appendedList;
                        console.log(resultList)
                        if (shouldAppend) {
                            appendedList = me.state.list;
                            $.each(resultList, function (i, item) {
                                appendedList.push(item);
                            });

                            mui('#pullrefresh')
                                .pullRefresh()
                                .endPullupToRefresh((appendedList.length == maxCount)); //refresh completed

                            me.setState({
                                list: appendedList,
                                currType: Fn,
                                total: appendedList.length,
                            });
                        }
                        else {
                            me.setState({
                                list: resultList,
                                currType: Fn,
                            });
                        }
                    }
                    else {
                        alert(data.desc);
                    }
                }
            }, lf.api.statistics.ReportListByStatus);
        },
        componentWillMount: function () {
            var me = this;
            let timeList = [0, 1, 2, 3];//0:all,1:day,2:week,3:month
            timeList.map((i)=> {
                ajax({
                    type: 'POST',
                    data: {
                        staffId: me.props.user.id,
                        eventReportType: '',
                        timeType: i,
                    },
                    success: function (data) {
                        let list = me.state.maxCount;
                        list[i] = data.maxCount;
                        me.setState({
                            maxCount: list
                        })
                    }
                }, lf.api.statistics.ReportListByStatus)
            })
            me.getList();
            lf.appJs.refresh();
        },
        render: function () {
            return (
                <div className="report-list">
                    {TYPE == CHECK ?
                        <Header maxCount={this.state.maxCount} getList={this.getList} user={this.state.user}
                                counts={this.state.headerCounts } resetPage={this.props.resetPage}
                        /> : null}
                    <ListGroup data={this.state.list} getList={this.getList} user={this.state.user}/>
                </div>
            )
        },
        componentWillReceiveProps: function (nextProps) {
            var page = nextProps.page;
            this.getList(page, true, this.state.currType);
        },
    });

    var PullRefreshCon = React.createClass({
        getInitialState: function () {
            return {
                page: 1,
            }
        },
        resetPage: function () {//todo 存在header 的上拉加载页面必须啊
            this.state.page = 1;
        },
        pullupFn: function () {
            var newPage = ++this.state.page;
            this.setState({
                page: newPage
            });
        },
        render: function () {
            var me = this;
            return <PullRefresh pullupFn={me.pullupFn}
                                data={<Root user={me.props.user} page={me.state.page} resetPage={me.resetPage}/>}/>;
        }
    });
    lf.appJs.getUser((user)=> {
        r.render(
            <PullRefreshCon user={user}/>,
            document.getElementById('root'), function () {
                $('#root').css('background', 'none');
            }
        )
    })
})(liefeng, React)